package test.reader;

import org.springframework.batch.item.*;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.RowMapper;

import test.pojo.Person;


import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/8/2 16:03
 * @ Description:
 */
@Configuration
public class MyJdbcReaderConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public ItemReader<Person> dbJdbcReader() {
        JdbcPagingItemReader<Person> personJdbcPagingItemReader = new JdbcPagingItemReader<>();
        personJdbcPagingItemReader.setDataSource(dataSource);
        personJdbcPagingItemReader.setFetchSize(500000);
        personJdbcPagingItemReader.setRowMapper(new RowMapper<Person>() {
            @Override
            public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
                Person person = new Person();
                return person.setId(rs.getString(1))
                        .setName(rs.getString(2))
                        .setSex(rs.getString(3))
                        .setAge(rs.getString(4))
                        .setAddress(rs.getString(5))
                        .setEmail(rs.getString(6))
                        .setTel(rs.getString(7));

            }
        });
        MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider();
        provider.setSelectClause("id , name , sex , age , address , email , tel");
        provider.setFromClause("from t_person");
        HashMap<String, Order> sort = new HashMap<>(1);
        sort.put("id" , Order.ASCENDING);
        provider.setSortKeys(sort);
        personJdbcPagingItemReader.setQueryProvider(provider);
        return personJdbcPagingItemReader;
    }
}
